package com.djj.nanny.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djj.nanny.entity.*;
import jakarta.annotation.Resource;
import com.djj.nanny.enumClass.OrderStatus;
import com.djj.nanny.exception.ServiceException;
import com.djj.nanny.mapper.ServiceCategoryMapper;
import com.djj.nanny.mapper.ServiceOrderMapper;
import com.djj.nanny.mapper.ServiceStaffMapper;
import com.djj.nanny.mapper.UserMapper;
import com.djj.nanny.service.ServiceStaffService;
import com.djj.nanny.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ServiceStaffServiceImpl implements ServiceStaffService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceStaffServiceImpl.class);

    @Resource
    private ServiceStaffMapper serviceStaffMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ServiceCategoryMapper categoryMapper;

    @Resource
    private ServiceOrderMapper orderMapper;

    @Resource
    private StaffServiceItemServiceImpl staffServiceItemService;

    /**
     * 创建服务人员
     */
    @Transactional(rollbackFor = Exception.class)
    public void createServiceStaff(ServiceStaff staff) {
        // 检查用户是否存在
        User user = userMapper.selectById(staff.getUserId());
        if (user == null) {
            throw new ServiceException("关联用户不存在");
        }

        // 检查是否已经是服务人员
        if (serviceStaffMapper.selectOne(new LambdaQueryWrapper<ServiceStaff>()
                .eq(ServiceStaff::getUserId, staff.getUserId())) != null) {
            throw new ServiceException("该用户已经是服务人员");
        }

        // 设置初始值
        staff.setRating(new BigDecimal("5.0"));
        staff.setTotalOrders(0);
        staff.setCompletionRate(new BigDecimal("100.0"));

        // 保存服务人员信息
        if (serviceStaffMapper.insert(staff) <= 0) {
            throw new ServiceException("创建服务人员失败");
        }

        LOGGER.info("创建服务人员成功: {}", staff.getId());
    }

    /**
     * 更新服务人员信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateServiceStaff(ServiceStaff staff) {
        // 检查服务人员是否存在
        if (serviceStaffMapper.selectById(staff.getId()) == null) {
            throw new ServiceException("服务人员不存在");
        }

        // 更新服务人员信息
        if (serviceStaffMapper.updateById(staff) <= 0) {
            throw new ServiceException("更新服务人员信息失败");
        }

        LOGGER.info("更新服务人员信息成功: {}", staff.getId());
    }

    /**
     * 填充用户信息
     */
    public void fillUserInfo(ServiceStaff staff) {
        if (staff != null && staff.getUserId() != null) {
            User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                    .eq(User::getId, staff.getUserId())

            );
            staff.setUser(user);
        }
    }

    /**
     * 批量填充用户信息
     */
    private void fillUserInfo(List<ServiceStaff> staffList) {
        if (staffList != null && !staffList.isEmpty()) {
            // 提取所有用户ID
            List<Long> userIds = staffList.stream()
                    .map(ServiceStaff::getUserId)
                    .collect(Collectors.toList());
            
            // 批量查询未删除的用户信息
            List<User> users = userMapper.selectList(
                new LambdaQueryWrapper<User>()
                    .in(User::getId, userIds)

            );
            
            // 构建用户ID到用户信息的映射
            Map<Long, User> userMap = users.stream()
                    .collect(Collectors.toMap(User::getId, user -> user));
            
            // 填充用户信息
            staffList.forEach(staff -> staff.setUser(userMap.get(staff.getUserId())));
        }
    }

    /**
     * 批量填充服务类型信息
     */
    private void fillCategories(List<ServiceStaff> staffList) {
        if (staffList != null && !staffList.isEmpty()) {
            try {
                // 收集所有服务类型名称
                Set<String> categoryNames = new HashSet<>();
                for (ServiceStaff staff : staffList) {
                    if (staff.getServiceType() != null) {
                        List<String> names = JsonUtils.parseArray(staff.getServiceType(), String.class);
                        if (names != null) {
                            categoryNames.addAll(names);
                        }
                    }
                }

                if (!categoryNames.isEmpty()) {
                    // 批量查询服务类型信息
                    List<ServiceCategory> categories = categoryMapper.selectList(
                        new LambdaQueryWrapper<ServiceCategory>()
                            .in(ServiceCategory::getCategoryName, categoryNames)
                            .eq(ServiceCategory::getIsDeleted, 0)
                            .orderByAsc(ServiceCategory::getSortNum)
                    );
                    Map<String, ServiceCategory> categoryMap = categories.stream()
                            .collect(Collectors.toMap(ServiceCategory::getCategoryName, category -> category));

                    // 为每个服务人员填充服务类型信息
                    for (ServiceStaff staff : staffList) {
                        if (staff.getServiceType() != null) {
                            List<String> names = JsonUtils.parseArray(staff.getServiceType(), String.class);
                            if (names != null) {
                                List<ServiceCategory> staffCategories = names.stream()
                                        .map(categoryMap::get)
                                        .filter(Objects::nonNull)
                                        .collect(Collectors.toList());
                                staff.setCategories(staffCategories);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error("批量填充服务类型信息失败", e);
            }
        }
    }

    /**
     * 获取服务人员详情时填充服务项目信息
     */
    private void fillServiceItems(ServiceStaff staff) {
        if (staff != null) {
            List<StaffServiceItem> serviceItems = staffServiceItemService.getServiceItems(staff.getId());
            staff.setServiceItems(serviceItems);
        }
    }

    /**
     * 批量填充服务项目信息
     */
    private void fillServiceItems(List<ServiceStaff> staffList) {
        if (staffList != null && !staffList.isEmpty()) {
            for (ServiceStaff staff : staffList) {
                fillServiceItems(staff);
            }
        }
    }

    /**
     * 获取服务人员详情
     */
    public ServiceStaff getServiceStaffById(Long id) {
        ServiceStaff staff = serviceStaffMapper.selectOne(
            new LambdaQueryWrapper<ServiceStaff>()
                .eq(ServiceStaff::getId, id)
                .eq(ServiceStaff::getIsDeleted, 0)  // 只查询未删除的服务人员
        );
        if (staff == null) {
            throw new ServiceException("服务人员不存在");
        }
        fillUserInfo(staff);
        return staff;
    }
    /**
     * 根据用户ID查询服务人员信息
     */
    public ServiceStaff getServiceStaffByUserId(Long userId) {
        LOGGER.info("userId:{}",userId);
        ServiceStaff staff = serviceStaffMapper.selectOne(
            new LambdaQueryWrapper<ServiceStaff>()
                .eq(ServiceStaff::getUserId, userId)
                // .eq(ServiceStaff::getIsDeleted, 0)
        );
        if (staff == null) {
            throw new ServiceException("服务人员不存在");
        }
        fillUserInfo(staff);
        return staff;
    }

    /**
     * 分页查询服务人员列表
     */
    public Page<ServiceStaff> getServiceStaffsByPage(String name, String serviceType, 
            Integer pageNum, Integer pageSize, String workArea, BigDecimal minRating) {
        LambdaQueryWrapper<ServiceStaff> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (name != null && !name.trim().isEmpty()) {
            // 查询未删除的用户中匹配名字的用户ID列表
            List<Long> ids = userMapper.selectList(
                new LambdaQueryWrapper<User>()
                    .like(User::getName, name)
            ).stream()
             .map(User::getId)
             .collect(Collectors.toList());
            
            if (!ids.isEmpty()) {
                queryWrapper.in(ServiceStaff::getUserId, ids);
            } else {
                // 如果没有匹配的用户，返回空结果
                return new Page<>(pageNum, pageSize);
            }
        }

        // 添加工作区域过滤条件
        if (workArea != null && !workArea.trim().isEmpty()) {
            queryWrapper.like(ServiceStaff::getWorkArea, workArea);
        }

        // 添加最低评分过滤条件
        if (minRating != null) {
            queryWrapper.ge(ServiceStaff::getRating, minRating);
        }

        // 只查询未删除的服务人员
        queryWrapper.eq(ServiceStaff::getIsDeleted, 0);
        // 按评分降序排序
        queryWrapper.orderByDesc(ServiceStaff::getRating);
        
        // 执行分页查询
        Page<ServiceStaff> page = serviceStaffMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        
        // 如果需要按服务类型筛选
        if (serviceType != null && !serviceType.trim().isEmpty()) {
            String searchType = serviceType.trim();
            // 过滤包含指定服务类型的记录
            List<ServiceStaff> filteredRecords = page.getRecords().stream()
                .filter(staff -> {
                    try {
                        List<String> types = JsonUtils.parseArray(staff.getServiceType(), String.class);
                        return types != null && types.contains(searchType);
                    } catch (Exception e) {
                        LOGGER.error("解析服务类型JSON失败: {}", staff.getServiceType(), e);
                        return false;
                    }
                })
                .collect(Collectors.toList());
            
            // 更新分页结果
            page.setRecords(filteredRecords);
            page.setTotal(filteredRecords.size());
        }
        
        // 填充用户信息
        fillUserInfo(page.getRecords());
        
        return page;
    }

    /**
     * 获取评分前10的服务人员
     */
    public List<ServiceStaff> getTopRatedStaff() {
        // 构建查询条件
        LambdaQueryWrapper<ServiceStaff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceStaff::getIsDeleted, 0)  // 只查询未删除的服务人员
                   .orderByDesc(ServiceStaff::getRating)  // 按评分降序排序
                   .last("LIMIT 10");  // 限制返回前10条记录
        
        List<ServiceStaff> staffList = serviceStaffMapper.selectList(queryWrapper);
        
        // 填充用户信息和服务类型信息
        fillUserInfo(staffList);
        fillCategories(staffList);
        
        return staffList;
    }

    /**
     * 删除服务人员(软删除)
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteServiceStaff(Long id) {
        // 检查服务人员是否存在且未删除
        ServiceStaff staff = serviceStaffMapper.selectOne(
            new LambdaQueryWrapper<ServiceStaff>()
                .eq(ServiceStaff::getId, id)
                .eq(ServiceStaff::getIsDeleted, 0)
        );
        if (staff == null) {
            throw new ServiceException("服务人员不存在");
        }

        // 检查是否存在未完成的订单
        Long unfinishedCount = orderMapper.selectCount(
            new LambdaQueryWrapper<ServiceOrder>()
                .eq(ServiceOrder::getStaffId, id)
                .eq(ServiceOrder::getIsDeleted, 0)  // 只检查未删除的订单
                .notIn(ServiceOrder::getOrderStatus, 
                    OrderStatus.COMPLETED.getValue(),
                    OrderStatus.CANCELLED.getValue(),
                    OrderStatus.CLOSED.getValue())
        );
        
        if (unfinishedCount > 0) {
            throw new ServiceException("该服务人员存在未完成的订单，不能删除");
        }

        // 执行软删除(手动设置isDeleted为1)
        ServiceStaff updateStaff = new ServiceStaff();
        updateStaff.setId(id);
        updateStaff.setIsDeleted(1);
        if (serviceStaffMapper.updateById(updateStaff) <= 0) {
            throw new ServiceException("删除服务人员失败");
        }

        LOGGER.info("服务人员软删除成功: {}", id);
    }



    /**
     * 根据服务项目查找可用的服务人员
     */
    public List<ServiceStaff> getAvailableStaffByServiceItem(Long serviceId) {
        // 查询所有提供该服务且状态正常的服务人员关联记录
        List<StaffServiceItem> staffServiceItems = staffServiceItemService.getStaffsByServiceItem(serviceId);
        if (staffServiceItems.isEmpty()) {
            return new ArrayList<>();
        }

        // 提取服务人员ID列表
        List<Long> staffIds = staffServiceItems.stream()
                .map(StaffServiceItem::getStaffId)
                .collect(Collectors.toList());

        // 构建查询条件
        LambdaQueryWrapper<ServiceStaff> queryWrapper = new LambdaQueryWrapper<ServiceStaff>()
                .in(ServiceStaff::getId, staffIds)
                .eq(ServiceStaff::getIsDeleted, 0)  // 未删除的服务人员
                .orderByDesc(ServiceStaff::getRating)  // 按评分降序
                .orderByDesc(ServiceStaff::getCompletionRate);  // 按完成率降序

        // 执行查询
        List<ServiceStaff> staffList = serviceStaffMapper.selectList(queryWrapper);

        // 填充关联信息
        fillUserInfo(staffList);
        fillCategories(staffList);
        fillServiceItems(staffList);

        return staffList;
    }
} 